﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ServerLib;
using System.Collections;

namespace ChatClient
{
    public partial class Login : Form
    {
        private IRemoteServer remserv2;// A remote object for the server
        public delegate void LoginEventHadler(ClientInfo clinfo);// Delegate for Login event
        public event LoginEventHadler LoginEvent;// event that generate when new user is logined

        public Login(IRemoteServer remserv)
        {
            remserv2 = remserv;
            this.AcceptButton = buttonEnter;
            this.CancelButton = buttonCancel;
            InitializeComponent();
        }

        private void buttonRegistration_Click(object sender, EventArgs e)
        {
            Registration rf = new Registration(remserv2);
            rf.ShowDialog();
        }

        private void buttonEnter_Click(object sender, EventArgs e)
        {
            ArrayList al = remserv2.GetListOfClients();
            if(al.Contains(textBoxLogin.Text))
            {
                MessageBox.Show("This user already logined");
                return;
            }
            if (LoginSucssesfull(textBoxLogin.Text, textBoxPassword.Text))
            {

                remserv2.AddClient(textBoxLogin.Text);
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
                MessageBox.Show("Error!");
        }

        /// <summary>
        /// Check the required information and return true if logined sucsessful, and 
        /// transfer information about logined user
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        /// <returns></returns>

        private bool LoginSucssesfull(string login, string password)
        {
           ClientInfo clinf = remserv2.GetClientInfo(login);
           if (remserv2.CheckPassword(login, password))
           {
               if (LoginEvent != null)
               {
                   LoginEvent(clinf);
               }
               return true;
           }
           else return false;
        }
    }
}
